import _debounce from 'lodash/debounce';
import { DependencyList, useEffect, useMemo, useRef, useState } from 'react';
import {
  autorun,
  IObservable,
} from '@opensumi/monaco-editor-core/esm/vs/base/common/observableInternal';
import { DisposableStore, IDisposable } from '../utils';

export function useDisposable(
  callback: () => IDisposable | IDisposable[],
  deps: DependencyList = []
) {
  useEffect(() => {
    const disposableStore = new DisposableStore();
    const disposables = callback();
    if (Array.isArray(disposables)) {
      disposables.forEach((disposable) => {
        disposableStore.add(disposable);
      });
    } else {
      disposableStore.add(disposables);
    }

    return () => {
      disposableStore.dispose();
    };
  }, deps);
}

export const useAutorun = <T>(observable: IObservable<T>): T => {
  const [value, setValue] = useState<T>(observable.get());

  useDisposable(
    () =>
      autorun((reader) => {
        setValue(observable.read(reader));
      }),
    [observable]
  );

  return value;
};
